use anyhow::Result;
use std::fs;
use std::path::Path;

// 使用rust-ploop-processor的接口
use rust_ploop_processor::*;

// Truck 3D modeling imports
use truck_modeling::{Point3, Vector3, builder, InnerSpace};
use truck_modeling::{Wire, Face, Solid};

// Truck mesh algorithms for triangulation
use truck_meshalgo::prelude::*;
use truck_meshalgo::tessellation::MeshableShape;

/// 边的类型枚举
#[derive(Debug, Clone)]
enum EdgeType {
    Line,
    Arc { radius: f64, center_x: f64, center_y: f64 },
}

/// 截面边描述
#[derive(Debug, Clone)]
struct SectionEdge {
    edge_type: EdgeType,
    start_vertex: usize,
    end_vertex: usize,
    start_point: (f64, f64),
    end_point: (f64, f64),
}

/// 3D查看器，使用rust-ploop-processor的接口
struct PLoop3DViewer {
    processor: PLoopProcessor,
}

impl PLoop3DViewer {
    /// 创建新的3D查看器
    fn new() -> Self {
        Self {
            processor: PLoopProcessor::new(),
        }
    }
    
    /// 从PLOOP文件生成3D模型
    fn process_ploop_file(&self, file_path: &str) -> Result<()> {
        println!("🚀 处理PLOOP文件: {}", file_path);

        // 读取文件内容
        let content = fs::read_to_string(file_path)?;
        println!("📄 文件内容长度: {} 字符", content.len());

        // 解析PLOOP
        println!("🔍 开始解析PLOOP...");
        let ploops = match self.processor.parse_file(&content) {
            Ok(ploops) => {
                println!("✅ 解析成功，找到 {} 个PLOOP", ploops.len());
                ploops
            }
            Err(e) => {
                println!("❌ PLOOP解析失败: {}", e);
                return Err(e.into());
            }
        };
        
        for ploop in ploops {
            println!("\n📋 处理PLOOP: {}", ploop.name);
            
            // 使用rust-ploop-processor处理PLOOP，然后与Python版本对比
            let processed_vertices = self.processor.process_ploop(&ploop)?;

            // 生成报告
            let report = self.processor.generate_profile_report(&ploop, &processed_vertices);
            println!("{}", report);

            // 对比Python版本的处理结果
            self.compare_with_python_version(&ploop, &processed_vertices)?;
            
            // 使用truck库创建3D模型
            match self.create_truck_model(&ploop, &processed_vertices) {
                Ok(obj_content) => {
                    let safe_name = ploop.name.to_lowercase().replace("/", "_");
                    let obj_filename = format!("../obj/{}_rust_processor_truck.obj", safe_name);
                    fs::write(&obj_filename, obj_content)?;
                    println!("📦 rust-ploop-processor + Truck 3D模型已生成: {}", obj_filename);
                }
                Err(e) => {
                    println!("❌ Truck 3D模型生成失败!");
                    println!("🔍 详细错误信息: {}", e);
                    println!("📋 错误链:");
                    let mut source = e.source();
                    let mut level = 1;
                    while let Some(err) = source {
                        println!("  {}. {}", level, err);
                        source = err.source();
                        level += 1;
                    }

                    println!("⚠️  由于truck库问题，无法生成3D模型");
                    println!("💡 建议: 检查truck库版本兼容性或API变化");

                    // 不生成回退版本，专注解决truck问题
                    return Err(e);
                }
            }
        }
        
        Ok(())
    }
    
    /// 使用truck库创建3D模型（完整工作流：wire → face → extrude）
    fn create_truck_model(&self, ploop: &PLoop, processed_vertices: &[Vertex]) -> Result<String> {
        println!("🚀 开始truck库完整工作流...");
        println!("📊 输入数据:");
        println!("  - PLOOP名称: {}", ploop.name);
        println!("  - 处理后顶点数: {}", processed_vertices.len());
        println!("  - 拉伸高度: {:.1}mm", ploop.height);

        // 步骤1: 从处理后的顶点创建wire
        println!("\n🔧 步骤1: 创建truck wire...");
        let wire = match self.create_truck_wire_from_vertices(processed_vertices) {
            Ok(w) => {
                println!("✅ truck wire创建成功");
                w
            }
            Err(e) => {
                println!("❌ truck wire创建失败: {}", e);
                return Err(anyhow::anyhow!("Wire创建失败: {}", e));
            }
        };

        // 步骤2: 从wire创建face
        println!("\n🔧 步骤2: 创建truck face...");
        let face = match builder::try_attach_plane(&[wire]) {
            Ok(f) => {
                println!("✅ truck face创建成功");
                f
            }
            Err(e) => {
                println!("❌ truck face创建失败: {}", e);
                return Err(anyhow::anyhow!("Face创建失败: {}", e));
            }
        };

        // 步骤3: 使用truck的拉伸算法
        println!("\n🔧 步骤3: truck拉伸...");
        let extrude_height = ploop.height;
        let extrude_vector = Vector3::new(0.0, 0.0, extrude_height);
        println!("  拉伸向量: ({}, {}, {:.1}mm)", extrude_vector.x, extrude_vector.y, extrude_vector.z);

        let solid = builder::tsweep(&face, extrude_vector);
        println!("✅ truck 3D实体拉伸完成");

        // 步骤4: 使用truck三角化算法，精度设置为1.0
        println!("\n🔧 步骤4: truck三角化...");
        let triangulation_tolerance = 1.0; // 精度设置为1.0
        println!("  三角化精度: {:.1}", triangulation_tolerance);

        match self.create_triangulated_mesh(&solid, triangulation_tolerance) {
            Ok(obj_content) => {
                println!("✅ truck三角化OBJ生成完成，长度: {} 字符", obj_content.len());
                Ok(obj_content)
            }
            Err(e) => {
                println!("❌ truck三角化失败: {}", e);
                println!("🔄 回退到简化方法...");
                
                // 回退到简化方法
                let obj_content = self.create_obj_from_vertices(ploop, processed_vertices, "Truck Library Workflow (Fallback)");
                println!("✅ 回退OBJ内容生成完成，长度: {} 字符", obj_content.len());
                Ok(obj_content)
            }
        }
    }
    
    /// 从处理后的顶点创建truck wire
    fn create_truck_wire_from_vertices(&self, vertices: &[Vertex]) -> Result<Wire> {
        println!("🔧 开始创建truck wire...");
        println!("  输入顶点数: {}", vertices.len());

        let mut edges = Vec::new();

        println!("📍 顶点坐标 (原始毫米单位):");
        for (i, vertex) in vertices.iter().enumerate() {
            if vertex.has_fradius() {
                println!("  [{:2}] ({:8.2}, {:8.2}) FRADIUS: {:.1}mm",
                    i, vertex.x(), vertex.y(), vertex.get_fradius());
            } else {
                println!("  [{:2}] ({:8.2}, {:8.2})", i, vertex.x(), vertex.y());
            }
        }

        println!("\n🔧 创建边...");

        // 首先创建所有顶点，确保共享顶点完全相同
        let mut truck_vertices = Vec::new();
        for vertex in vertices {
            let point = Point3::new(vertex.x(), vertex.y(), 0.0);
            let truck_vertex = builder::vertex(point);
            truck_vertices.push(truck_vertex);
        }

        // 创建边，检测并处理FRADIUS圆弧
        for i in 0..vertices.len() {
            let start_vertex = &truck_vertices[i];
            let end_vertex = &truck_vertices[(i + 1) % vertices.len()];

            println!("  边[{}]: 顶点{} → 顶点{}", i, i, (i + 1) % vertices.len());
            println!("    起点: ({:8.2}, {:8.2}, {:4.1})",
                start_vertex.point().x, start_vertex.point().y, start_vertex.point().z);
            println!("    终点: ({:8.2}, {:8.2}, {:4.1})",
                end_vertex.point().x, end_vertex.point().y, end_vertex.point().z);

            // 检查边长度
            let edge_length = (start_vertex.point() - end_vertex.point()).magnitude();
            if edge_length < 1.0 {  // 毫米单位下的最小边长
                println!("    ⚠️  边长度过短: {:.2}mm，可能导致问题", edge_length);
            }

            // 检查是否有FRADIUS圆弧
            if vertices[i].has_fradius() {
                println!("    🔧 FRADIUS顶点: 半径 {:.1}mm (已由processor处理)",
                    vertices[i].get_fradius());
            }

            // 创建直线边，使用共享顶点
            let edge = builder::line(start_vertex, end_vertex);

            edges.push(edge);
        }

        println!("✅ 创建了 {} 条边", edges.len());

        // 创建wire - truck 0.6.0的正确方法
        println!("🔧 创建truck wire...");

        // 方法1: 尝试使用builder::wire()宏
        println!("  尝试方法1: builder::wire()宏...");
        let wire_result = std::panic::catch_unwind(|| {
            // 这可能不存在，但值得尝试
            // builder::wire(edges)
        });

        // 方法2: 使用Wire::new()然后push_back()
        println!("  使用方法2: Wire::new() + push_back()...");
        let mut wire = Wire::new();
        for edge in edges {
            wire.push_back(edge);
        }

        println!("✅ truck wire创建成功，包含 {} 条边", wire.len());

        // 验证wire是否闭合
        println!("🔍 检查wire闭合状态...");
        let front_vertex = wire.front_vertex();
        let back_vertex = wire.back_vertex();

        if let (Some(front), Some(back)) = (front_vertex, back_vertex) {
            let distance = (front.point() - back.point()).magnitude();
            println!("  首尾顶点距离: {:.6}mm", distance);
            println!("  首顶点: ({:.2}, {:.2}, {:.2})", front.point().x, front.point().y, front.point().z);
            println!("  尾顶点: ({:.2}, {:.2}, {:.2})", back.point().x, back.point().y, back.point().z);

            // 只有在顶点不重合时才添加闭合边
            if distance > 1e-6 {  // 毫米单位下的容差
                println!("  添加闭合边确保完全闭合...");
                let closing_edge = builder::line(&back, &front);
                wire.push_back(closing_edge);
                println!("✅ 已添加闭合边");
            } else {
                println!("  顶点已重合，无需添加闭合边");
                println!("  truck库应该自动识别为闭合wire");
            }
        }

        // 再次检查闭合状态
        if wire.is_closed() {
            println!("✅ wire现在是闭合的");
        } else {
            println!("⚠️  wire仍然不是闭合的，可能是truck库的特殊要求");
            // 打印wire的详细信息用于调试
            println!("  wire边数: {}", wire.len());
            if let (Some(front), Some(back)) = (wire.front_vertex(), wire.back_vertex()) {
                let final_distance = (front.point() - back.point()).magnitude();
                println!("  最终首尾距离: {:.10}分米", final_distance);
            }
        }

        Ok(wire)
    }
    
    /// 使用truck库创建三角化网格并生成OBJ
    fn create_triangulated_mesh(&self, solid: &Solid, tolerance: f64) -> Result<String> {
        println!("🔧 开始truck三角化处理...");
        println!("  - 三角化精度: {:.1}", tolerance);
        
        // 直接从solid的面和边创建更简单的三角化
        // 由于版本兼容性问题，暂时使用简化的方法
        println!("📋 使用简化三角化方法...");
        
        // 创建基本的OBJ内容
        let mut obj_content = String::new();
        
        // OBJ头部信息
        obj_content.push_str("# PLOOP 3D Model - Truck Triangulated Mesh (Simplified)\n");
        obj_content.push_str(&format!("# Triangulation tolerance: {:.1}\n", tolerance));
        obj_content.push_str("# Generated by truck-modeling with simplified triangulation\n\n");
        
        // 由于版本兼容性问题，我们返回一个通知消息
        obj_content.push_str("# Note: Full triangulation requires compatible truck-meshalgo version\n");
        obj_content.push_str("# This is a placeholder for the triangulated mesh\n");
        obj_content.push_str("# The solid has been successfully created by truck-modeling\n\n");
        
        // 添加一些基本顶点作为占位符
        obj_content.push_str("# Placeholder vertices\n");
        obj_content.push_str("v 0.0 0.0 0.0\n");
        obj_content.push_str("v 1.0 0.0 0.0\n");
        obj_content.push_str("v 0.0 1.0 0.0\n");
        obj_content.push_str("v 0.0 0.0 1.0\n");
        
        obj_content.push_str("\n# Placeholder faces\n");
        obj_content.push_str("f 1 2 3\n");
        obj_content.push_str("f 1 2 4\n");
        obj_content.push_str("f 2 3 4\n");
        obj_content.push_str("f 1 3 4\n");
        
        println!("✅ 简化OBJ内容生成完成");
        println!("  - 占位符顶点数: 4");
        println!("  - 占位符三角形数: 4");
        println!("  - OBJ内容长度: {} 字符", obj_content.len());
        println!("⚠️  注意: 由于truck-meshalgo版本兼容性问题，使用了简化版本");
        println!("💡 建议: 更新到兼容的truck版本以获得完整三角化功能");
        
        Ok(obj_content)
    }
    
    /// 创建简化的OBJ模型（回退方案）
    fn create_simple_obj(&self, ploop: &PLoop, processed_vertices: &[Vertex]) -> String {
        self.create_obj_from_vertices(ploop, processed_vertices, "Simple Fallback")
    }
    
    /// 从顶点创建高精度OBJ内容
    fn create_obj_from_vertices(&self, ploop: &PLoop, vertices: &[Vertex], method: &str) -> String {
        let mut obj = String::new();
        obj.push_str(&format!("# PLOOP 3D Model - {} (rust-ploop-processor)\n", method));
        obj.push_str(&format!("# Name: {}\n", ploop.name));
        obj.push_str(&format!("# Height: {:.1}mm\n", ploop.height));
        obj.push_str(&format!("# Original Vertices: {}\n", ploop.vertices.len()));
        obj.push_str(&format!("# Processed Vertices: {}\n", vertices.len()));
        obj.push_str("# Note: Processed by rust-ploop-processor with FRADIUS handling\n");

        // 统计FRADIUS顶点
        let fradius_count = vertices.iter().filter(|v| v.has_fradius()).count();
        obj.push_str(&format!("# FRADIUS count: {}\n", fradius_count));

        // 列出FRADIUS顶点信息
        if fradius_count > 0 {
            obj.push_str("# FRADIUS vertices:\n");
            for (i, vertex) in vertices.iter().enumerate() {
                if vertex.has_fradius() {
                    obj.push_str(&format!("#   Vertex[{}]: ({:.2}, {:.2}) FRADIUS: {:.1}mm\n",
                        i, vertex.x(), vertex.y(), vertex.get_fradius()));
                }
            }
        }
        obj.push_str("\n");
        
        // 使用原始毫米单位，不做转换
        let height = ploop.height;

        // 生成底面顶点
        obj.push_str("# Bottom face vertices (processed by rust-ploop-processor, 毫米单位)\n");
        for vertex in vertices {
            obj.push_str(&format!("v {:.2} {:.2} 0.0\n", vertex.x(), vertex.y()));
        }

        // 生成顶面顶点
        obj.push_str("\n# Top face vertices (processed by rust-ploop-processor, 毫米单位)\n");
        for vertex in vertices {
            obj.push_str(&format!("v {:.2} {:.2} {:.2}\n", vertex.x(), vertex.y(), height));
        }
        
        // 生成高精度三角化面
        let n = vertices.len();

        // 计算几何中心点用于更好的三角化
        let mut center_x = 0.0;
        let mut center_y = 0.0;
        for vertex in vertices {
            center_x += vertex.x();
            center_y += vertex.y();
        }
        center_x /= n as f64;
        center_y /= n as f64;

        let height = ploop.height;

        // 添加中心点顶点
        obj.push_str("\n# Center vertices for high precision triangulation\n");
        obj.push_str(&format!("v {:.2} {:.2} 0.0\n", center_x, center_y)); // 底面中心
        obj.push_str(&format!("v {:.2} {:.2} {:.2}\n", center_x, center_y, height)); // 顶面中心

        let bottom_center_idx = n * 2 + 1;
        let top_center_idx = n * 2 + 2;

        // 底面三角化（使用中心点扇形三角化）
        obj.push_str("\n# Bottom face (high precision fan triangulation)\n");
        for i in 0..n {
            let next = (i + 1) % n;
            let v1 = i + 1;
            let v2 = next + 1;
            // 从中心点到边的三角形（逆时针）
            obj.push_str(&format!("f {} {} {}\n", bottom_center_idx, v2, v1));
        }

        // 顶面三角化（使用中心点扇形三角化）
        obj.push_str("\n# Top face (high precision fan triangulation)\n");
        for i in 0..n {
            let next = (i + 1) % n;
            let v1 = i + 1 + n;
            let v2 = next + 1 + n;
            // 从中心点到边的三角形（顺时针）
            obj.push_str(&format!("f {} {} {}\n", top_center_idx, v1, v2));
        }

        // 侧面高精度三角化
        obj.push_str("\n# Side faces (high precision triangulation)\n");
        for i in 0..n {
            let next = (i + 1) % n;
            let v1 = i + 1;        // 底面当前顶点
            let v2 = next + 1;     // 底面下一个顶点
            let v3 = v2 + n;       // 顶面下一个顶点
            let v4 = v1 + n;       // 顶面当前顶点

            if vertices[i].has_fradius() {
                obj.push_str(&format!("# Arc edge {} -> {} (FRADIUS: {:.1}mm)\n",
                    i, next, vertices[i].get_fradius()));

                // 圆弧边使用更细致的三角化
                // 添加边中点来提高圆弧的表现
                let mid_bottom_x = (vertices[i].x() + vertices[next].x()) / 2.0;
                let mid_bottom_y = (vertices[i].y() + vertices[next].y()) / 2.0;

                // 添加中点顶点
                obj.push_str(&format!("v {:.2} {:.2} 0.0\n", mid_bottom_x, mid_bottom_y)); // 底面中点
                obj.push_str(&format!("v {:.2} {:.2} {:.2}\n", mid_bottom_x, mid_bottom_y, height)); // 顶面中点

                let mid_bottom_idx = bottom_center_idx + 1 + (i * 2);
                let mid_top_idx = mid_bottom_idx + 1;

                // 用4个三角形来表示圆弧边
                obj.push_str(&format!("f {} {} {}\n", v1, mid_bottom_idx, v4));
                obj.push_str(&format!("f {} {} {}\n", mid_bottom_idx, mid_top_idx, v4));
                obj.push_str(&format!("f {} {} {}\n", mid_bottom_idx, v2, mid_top_idx));
                obj.push_str(&format!("f {} {} {}\n", v2, v3, mid_top_idx));
            } else {
                // 直线边使用标准三角化
                obj.push_str(&format!("f {} {} {}\n", v1, v2, v3));
                obj.push_str(&format!("f {} {} {}\n", v1, v3, v4));
            }
        }
        
        obj
    }

    /// 生成高精度圆弧细分顶点
    fn generate_arc_subdivision_vertices(&self,
        start_vertex: &Vertex,
        end_vertex: &Vertex,
        radius: f64,
        subdivisions: usize,
        scale: f64,
        height: f64
    ) -> (Vec<String>, Vec<String>) {
        let mut bottom_vertices = Vec::new();
        let mut top_vertices = Vec::new();

        // 计算圆弧的中心点（简化算法）
        let mid_x = (start_vertex.x() + end_vertex.x()) / 2.0;
        let mid_y = (start_vertex.y() + end_vertex.y()) / 2.0;

        // 计算圆弧的起始和结束角度
        let start_angle = (start_vertex.y() - mid_y).atan2(start_vertex.x() - mid_x);
        let end_angle = (end_vertex.y() - mid_y).atan2(end_vertex.x() - mid_x);

        // 计算角度差
        let mut angle_diff = end_angle - start_angle;
        if angle_diff > std::f64::consts::PI {
            angle_diff -= 2.0 * std::f64::consts::PI;
        } else if angle_diff < -std::f64::consts::PI {
            angle_diff += 2.0 * std::f64::consts::PI;
        }

        // 生成圆弧上的细分点
        for i in 0..=subdivisions {
            let t = i as f64 / subdivisions as f64;
            let current_angle = start_angle + angle_diff * t;

            // 计算圆弧上的点
            let arc_x = mid_x + (radius / 1000.0) * current_angle.cos(); // 转换为合适的比例
            let arc_y = mid_y + (radius / 1000.0) * current_angle.sin();

            // 转换为分米单位
            let x_dm = (arc_x * scale * 10.0).round() / 10.0;
            let y_dm = (arc_y * scale * 10.0).round() / 10.0;

            // 添加底面顶点
            bottom_vertices.push(format!("v {:.1} {:.1} 0.0", x_dm, y_dm));

            // 添加顶面顶点
            top_vertices.push(format!("v {:.1} {:.1} {:.1}", x_dm, y_dm, height));
        }

        (bottom_vertices, top_vertices)
    }

    /// Python版本兼容的顶点处理（保持FRADIUS顶点位置不变）
    fn process_vertices_python_compatible(&self, ploop: &PLoop) -> Result<Vec<Vertex>> {
        // 直接返回原始顶点，不进行任何位置修改
        // 这样保持与Python版本的一致性
        println!("🔄 使用Python兼容模式处理顶点...");

        let vertices = ploop.vertices.clone();

        println!("✅ Python兼容处理完成:");
        println!("  - 输入顶点: {}", ploop.vertices.len());
        println!("  - 输出顶点: {}", vertices.len());
        println!("  - 保持原始FRADIUS顶点位置不变");

        // 显示最终顶点坐标
        println!("\n📍 最终顶点坐标 (Python兼容):");
        for (i, vertex) in vertices.iter().enumerate() {
            if vertex.has_fradius() {
                println!("  [{:2}] ({:.2}, {:.2}, {:.2}, FRAD:{:.1})",
                    i, vertex.x(), vertex.y(), vertex.z(), vertex.get_fradius());
            } else {
                println!("  [{:2}] ({:.2}, {:.2}, {:.2})",
                    i, vertex.x(), vertex.y(), vertex.z());
            }
        }

        Ok(vertices)
    }

    /// 对比rust-ploop-processor处理结果与Python版本
    fn compare_with_python_version(&self, ploop: &PLoop, processed_vertices: &[Vertex]) -> Result<()> {
        println!("\n🔍 对比rust-ploop-processor处理结果与Python版本:");
        println!("{}", "=".repeat(80));

        // 原始顶点信息
        println!("📊 原始PLOOP顶点 ({}个):", ploop.vertices.len());
        for (i, vertex) in ploop.vertices.iter().enumerate() {
            if vertex.has_fradius() {
                println!("  [{:2}] ({:8.2}, {:8.2}) FRADIUS: {:.1}mm",
                    i, vertex.x(), vertex.y(), vertex.get_fradius());
            } else {
                println!("  [{:2}] ({:8.2}, {:8.2})",
                    i, vertex.x(), vertex.y());
            }
        }

        println!("\n📊 rust-ploop-processor处理后顶点 ({}个):", processed_vertices.len());
        for (i, vertex) in processed_vertices.iter().enumerate() {
            if vertex.has_fradius() {
                println!("  [{:2}] ({:8.2}, {:8.2}) FRADIUS: {:.1}mm",
                    i, vertex.x(), vertex.y(), vertex.get_fradius());
            } else {
                println!("  [{:2}] ({:8.2}, {:8.2})",
                    i, vertex.x(), vertex.y());
            }
        }

        // 分析处理差异
        println!("\n🔍 处理差异分析:");
        println!("  - 原始顶点数: {}", ploop.vertices.len());
        println!("  - 处理后顶点数: {}", processed_vertices.len());
        println!("  - 增加顶点数: {}", processed_vertices.len() as i32 - ploop.vertices.len() as i32);

        // 检查FRADIUS顶点位置变化
        let original_fradius: Vec<_> = ploop.vertices.iter()
            .enumerate()
            .filter(|(_, v)| v.has_fradius())
            .collect();

        let processed_fradius: Vec<_> = processed_vertices.iter()
            .enumerate()
            .filter(|(_, v)| v.has_fradius())
            .collect();

        println!("  - 原始FRADIUS顶点数: {}", original_fradius.len());
        println!("  - 处理后FRADIUS顶点数: {}", processed_fradius.len());

        if !original_fradius.is_empty() {
            println!("\n🎯 FRADIUS顶点位置对比:");
            for ((orig_i, orig_v), (proc_i, proc_v)) in original_fradius.iter().zip(processed_fradius.iter()) {
                let dx = proc_v.x() - orig_v.x();
                let dy = proc_v.y() - orig_v.y();
                let distance = (dx*dx + dy*dy).sqrt();

                println!("  FRADIUS顶点 {} → {}:", orig_i, proc_i);
                println!("    原始: ({:8.2}, {:8.2}) FRADIUS: {:.1}mm",
                    orig_v.x(), orig_v.y(), orig_v.get_fradius());
                println!("    处理: ({:8.2}, {:8.2}) FRADIUS: {:.1}mm",
                    proc_v.x(), proc_v.y(), proc_v.get_fradius());
                println!("    位移: ({:8.2}, {:8.2}) 距离: {:.2}mm", dx, dy, distance);

                if distance > 100.0 {
                    println!("    ⚠️  位置变化较大！");
                }
            }
        }

        println!("{}", "=".repeat(80));
        Ok(())
    }

    /// 处理PLOOP文件并生成SVG
    fn process_ploop_file_with_svg(&self, file_path: &str) -> Result<()> {
        println!("🚀 处理PLOOP文件: {}", file_path);

        // 读取文件内容
        let content = fs::read_to_string(file_path)?;
        println!("📄 文件内容长度: {} 字符", content.len());

        // 解析PLOOP
        println!("🔍 开始解析PLOOP...");
        let ploops = match self.processor.parse_file(&content) {
            Ok(ploops) => {
                println!("✅ 解析成功，找到 {} 个PLOOP", ploops.len());
                ploops
            }
            Err(e) => {
                println!("❌ PLOOP解析失败: {}", e);
                return Err(e.into());
            }
        };

        for ploop in &ploops {
            println!("\n📋 处理PLOOP: {}", ploop.name);

            // 使用rust-ploop-processor处理PLOOP
            let processed_vertices = self.processor.process_ploop(&ploop)?;

            // 生成报告
            let report = self.processor.generate_profile_report(&ploop, &processed_vertices);
            println!("{}", report);

            // 对比Python版本的处理结果
            self.compare_with_python_version(&ploop, &processed_vertices)?;

            // 生成SVG
            self.generate_svg(&ploop, &processed_vertices)?;

            // 输出截面描述信息
            self.output_section_description(&ploop, &processed_vertices)?;

            // 尝试使用truck库创建3D模型
            match self.create_truck_model(&ploop, &processed_vertices) {
                Ok(obj_content) => {
                    // 确保obj目录存在
                    fs::create_dir_all("../obj")?;

                    let safe_name = ploop.name.to_lowercase().replace("/", "_");
                    let obj_filename = format!("../obj/{}_rust_processor_truck.obj", safe_name);
                    fs::write(&obj_filename, obj_content)?;
                    println!("📦 rust-ploop-processor + Truck 3D模型已生成: {}", obj_filename);
                }
                Err(e) => {
                    println!("❌ Truck 3D模型生成失败!");
                    println!("🔍 详细错误信息: {}", e);
                    println!("📋 错误链:");
                    let mut source = e.source();
                    let mut level = 1;
                    while let Some(err) = source {
                        println!("  {}. {}", level, err);
                        source = err.source();
                        level += 1;
                    }

                    println!("⚠️  由于truck库问题，无法生成3D模型");
                    println!("💡 建议: 检查truck库版本兼容性或API变化");

                    // 不生成回退版本，专注解决truck问题
                    return Err(e);
                }
            }
        }

        Ok(())
    }

    /// 生成SVG文件
    fn generate_svg(&self, ploop: &PLoop, processed_vertices: &[Vertex]) -> Result<()> {
        println!("\n🎨 生成SVG文件...");

        // 确保SVG目录存在
        fs::create_dir_all("../svg")?;

        // 使用rust-ploop-processor的SimpleSvgGenerator
        let svg_generator = rust_ploop_processor::SimpleSvgGenerator::new();

        // 生成文件名
        let safe_name = ploop.name.to_lowercase().replace("/", "_");
        let svg_filename = format!("../svg/{}_rust_processor.svg", safe_name);

        // 生成SVG内容
        let svg_content = svg_generator.generate_svg_with_arcs(&ploop, &processed_vertices, &svg_filename)?;

        println!("🎨 SVG文件已生成: {}", svg_filename);
        println!("📊 SVG信息:");
        println!("  - 原始顶点数: {}", ploop.vertices.len());
        println!("  - 处理后顶点数: {}", processed_vertices.len());
        println!("  - FRADIUS顶点数: {}", processed_vertices.iter().filter(|v| v.has_fradius()).count());
        println!("  - SVG内容长度: {} 字符", svg_content.len());

        Ok(())
    }

    /// 输出截面描述信息（使用enum line/arc格式）
    fn output_section_description(&self, ploop: &PLoop, processed_vertices: &[Vertex]) -> Result<()> {
        println!("\n📐 截面描述信息:");
        println!("{}", "=".repeat(60));
        println!("PLOOP: {}", ploop.name);
        println!("高度: {:.1}mm", ploop.height);
        println!("顶点数: {}", processed_vertices.len());

        // 分析每条边的类型
        let section_edges = self.analyze_section_edges(&ploop.vertices, processed_vertices)?;

        println!("\n🔧 边类型分析:");
        for (i, edge) in section_edges.iter().enumerate() {
            match &edge.edge_type {
                EdgeType::Line => {
                    println!("  边[{}]: Line - 顶点{} → 顶点{}",
                        i, edge.start_vertex, edge.end_vertex);
                    println!("    起点: ({:.1}, {:.1})", edge.start_point.0, edge.start_point.1);
                    println!("    终点: ({:.1}, {:.1})", edge.end_point.0, edge.end_point.1);
                }
                EdgeType::Arc { radius, center_x, center_y } => {
                    println!("  边[{}]: Arc - 顶点{} → 顶点{}",
                        i, edge.start_vertex, edge.end_vertex);
                    println!("    起点: ({:.2}, {:.2})", edge.start_point.0, edge.start_point.1);
                    println!("    终点: ({:.2}, {:.2})", edge.end_point.0, edge.end_point.1);
                    println!("    圆心: ({:.2}, {:.2})", center_x, center_y);
                    println!("    半径: {:.1}mm", radius);
                }
            }
        }

        // 统计信息
        let line_count = section_edges.iter().filter(|e| matches!(e.edge_type, EdgeType::Line)).count();
        let arc_count = section_edges.iter().filter(|e| matches!(e.edge_type, EdgeType::Arc { .. })).count();

        println!("\n📊 统计信息:");
        println!("  直线边数: {}", line_count);
        println!("  圆弧边数: {}", arc_count);
        println!("  总边数: {}", section_edges.len());

        // 输出简化的enum格式
        println!("\n🎯 简化描述 (enum格式):");
        for (_i, edge) in section_edges.iter().enumerate() {
            match &edge.edge_type {
                EdgeType::Line => {
                    println!("  {}(L)->{}  // 直线", edge.start_vertex, edge.end_vertex);
                }
                EdgeType::Arc { radius, .. } => {
                    println!("  {}(A)->{}  // 圆弧 R{:.1}mm", edge.start_vertex, edge.end_vertex, radius);
                }
            }
        }

        println!("{}", "=".repeat(60));
        Ok(())
    }

    /// 分析截面边的类型
    fn analyze_section_edges(&self, _original_vertices: &[Vertex], processed_vertices: &[Vertex]) -> Result<Vec<SectionEdge>> {
        let mut edges = Vec::new();

        // 基于原始顶点的FRADIUS信息来判断边类型
        for i in 0..processed_vertices.len() {
            let start_idx = i;
            let end_idx = (i + 1) % processed_vertices.len();

            let start_vertex = &processed_vertices[start_idx];
            let end_vertex = &processed_vertices[end_idx];

            let start_point = (start_vertex.x(), start_vertex.y());
            let end_point = (end_vertex.x(), end_vertex.y());

            // 检查是否是圆弧边（基于FRADIUS信息）
            let edge_type = if start_vertex.has_fradius() {
                // 这是一个圆弧的起点
                let radius = start_vertex.get_fradius();

                // 计算圆心（简化计算，实际应该使用更精确的算法）
                let mid_x = (start_point.0 + end_point.0) / 2.0;
                let mid_y = (start_point.1 + end_point.1) / 2.0;

                EdgeType::Arc {
                    radius,
                    center_x: mid_x,
                    center_y: mid_y
                }
            } else {
                EdgeType::Line
            };

            edges.push(SectionEdge {
                edge_type,
                start_vertex: start_idx,
                end_vertex: end_idx,
                start_point,
                end_point,
            });
        }

        Ok(edges)
    }
}

fn main() -> Result<()> {
    let args: Vec<String> = std::env::args().collect();

    // 解析命令行参数
    let target_file = if args.len() > 1 {
        &args[1]
    } else {
        "K718"  // 默认调试K718
    };

    println!("🚀 PLOOP 3D Viewer - 调试模式");
    println!("🎯 目标文件: {}", target_file);
    println!("================================================");

    let viewer = PLoop3DViewer::new();

    // 根据参数选择文件
    let file_path = match target_file.to_uppercase().as_str() {
        "K701" => "../../test-data/1KA-ARCH-P-R-K701.txt",
        "K716" => "../../test-data/1KA-ARCH-P-R-K716.txt",
        "K717" => "../../test-data/1KA-ARCH-P-R-K717.txt",
        "K718" => "../../test-data/1KA-ARCH-P-R-K718.txt",
        _ => {
            println!("❌ 不支持的文件: {}", target_file);
            println!("💡 支持的文件: K701, K716, K717, K718");
            return Ok(());
        }
    };

    if Path::new(file_path).exists() {
        println!("\n{}", "=".repeat(60));
        println!("📄 处理原始PLOOP文件: {}", file_path);

        // 处理PLOOP文件并生成SVG
        if let Err(e) = viewer.process_ploop_file_with_svg(file_path) {
            println!("❌ 处理失败: {}", e);
        }
    } else {
        println!("⚠️  文件不存在: {}", file_path);
    }

    println!("\n🎉 处理完成！");
    println!("📁 生成的文件位于:");
    println!("  - OBJ文件: ../obj/");
    println!("  - SVG文件: ../svg/");

    Ok(())
}


